package com.awei.controller;


import com.awei.domain.Result;
import com.awei.domain.po.User;
import com.awei.service.IUserService;

import com.awei.utils.JwtUtil;
import com.awei.utils.Md5Util;
import com.awei.utils.ThreadLocalUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.Pattern;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author awei
 * @since 2024-11-13
 */
@RestController
@RequestMapping("/user")

//用于启用方法参数的校验。它通常用 @Service @Controller
// 可以结合 @Valid 注解和 Bean Validation（如 Hibernate Validator）来实现参数的自动验证
@Validated
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 登录
     */
    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{2,5}$",message = "用户名长度在2-5之间") String username,
                           @Pattern(regexp = "^\\S{5,16}$",message = "密码长度在5-16之间") String password){
        if (username == null || password == null){
            return Result.error("用户名或密码为空");
        }
        password = Md5Util.getMD5String(password);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //创建条件
        queryWrapper.eq("username",username)
                    .eq("password",password);
        User one = userService.getOne(queryWrapper);
        if (one == null){
            return Result.error("用户名、密码错误");
        }
        //用户信息放入jwt中
        HashMap<String, Object> map = new HashMap<>();
        map.put("id",one.getId());
        map.put("username",one.getUsername());
        String token = JwtUtil.genToken(map);

        return Result.success(token);
    }

    /**
     * 查询所有
     * @return
     */
    @GetMapping()
    public Result getUser(){
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        //name中包含王
        userQueryWrapper.last("limit 10");
        return Result.success(userService.list(userQueryWrapper));
    }

    /**
     * 注册
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{2,5}$",message = "用户名长度在2-5之间") String username,
                           @Pattern(regexp = "^\\S{5,16}$",message = "密码长度在5-16之间") String password){
        //判断用户是否存在
        if (username == null || password == null){
            return Result.error("用户名或密码为空");
        }
        //1.创建warpper构造器
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //2.创建条件
        queryWrapper.eq("username",username);
        //3.调用service的查询方法
        User one = userService.getOne(queryWrapper);
        if (one != null){
            return Result.error("用户名已存在");
        }
        //4.md5对密码进行加密
        password = Md5Util.getMD5String(password);
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        userService.save(user);
        return Result.success("用户"+username+"添加成功");
    }


    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("/userInfo")
    public Result<User> getUserInfo(){
       /* //1.根据token获取用户信息
        String header = request.getHeader("Authorization");
        if (header==null) {
            return Result.error("请先登录");
        }
        //2.解析token
        Map<String, Object> map = JwtUtil.parseToken(header);
        //3.从map中获取用户id
        Integer id = (Integer) map.get("id");*/
        Integer id = ThreadLocalUtil.get();
        //4.获取用户信息
        User user = userService.getById(id);
        return Result.success(user);

    }

    /**
     * 更新用户信息
     * @param user
     * @return
     */
    @PutMapping("/update")
    public Result updateUser(@RequestBody User user){
        //更新用户信息
        userService.updateById(user);
        return Result.success();
    }

    //    更新用户头像
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam("avatarUrl") String avatarUrl) {
        Integer id = ThreadLocalUtil.get();
        //4.调用service的根据id查询用户信息
        User user = userService.getById(id);
        //5.更新用户头像
        user.setUserPic(avatarUrl);
        userService.updateById(user);
        //6.返回响应结果
        return Result.success();
    }

    //    更新用户密码
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> map) {
        String old_pwd = map.get("old_pwd");
        String new_pwd = map.get("new_pwd");
        String re_pwd = map.get("re_pwd");
        //判断旧密码是否正确
        //1.获取当前登录用户的id
        Integer id = ThreadLocalUtil.get();
        User user = userService.getById(id);
        if(!Md5Util.getMD5String(old_pwd).equals(user.getPassword())){
            return Result.error("旧密码错误");
        }
        //旧密码和新密码不能相同
        if(new_pwd.equals(old_pwd)){
            return Result.error("新密码和旧密码不能相同");
        }
        //新密码和确认密码必须相同
        if(!new_pwd.equals(re_pwd)){
            return Result.error("新密码和确认密码必须相同");
        }
        //3.调用service的更新密码方法
        user.setPassword(Md5Util.getMD5String(new_pwd));
        userService.updateById(user);
        //4.返回响应结果
        return Result.success();
    }

}
